package connections;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class BT2WebEasy extends MIDlet {

	//Change this
	String WEB_ADDRESS = "http://itp.nyu.edu/~dbo3/getNWrite.php";
/*
 * <?
	$stuff = $_REQUEST["data"];
	//make sure there is a directory called up in the same directory 
	//as this file and that the directory is world writable (777)
	$dest = fopen("./up/getNWrite.txt", 'a') ;
	fwrite($dest,$stuff );
	fclose($dest);
	print "Got $stuff ";
?>
*/

	//Change this to the hardware address of your bluetooth device (leave out the colons or dashes).
	String BT_ADDRESS = "00a096179a85";

	//Char from bt that triggers upload to web
	char TERMINATION_CHAR = 13;
	/*
	 * int pot = 65;
int light = 65;
int switcher = 0;


void setup()
{
  beginSerial(9600);
  pinMode(3, INPUT);      // sets the digital pin 7 as input
}

void loop()
{
  if (Serial.available() > 0){  //only send if you have hear back
   Serial.read();

   
    light  = analogRead(2);
    pot  = analogRead(3);
    switcher = digitalRead(3);


    Serial.print(pot,DEC);
    Serial.print(44, BYTE);
    Serial.print(light,DEC);
    Serial.print(44, BYTE);
    Serial.print(switcher,DEC);
    Serial.print(44, BYTE);
    Serial.print(10, BYTE);  //send a return

 }
  //delay(50);  //you might use this instead of if available
}

	 */

	//screen for the midlet interface
	Form mainForm;

	//bluetooth connection object using class below
	BT2WebRelayThread relay;

	protected void startApp() throws MIDletStateChangeException {
		//screen for the midlet
		mainForm = new Form("BT");
		//have the midlet display this screen
		Display.getDisplay(this).setCurrent(mainForm);
		//make a connection using class below at specified address
		relay = new BT2WebRelayThread();
		relay.start();

	}



	//obligatory method of  MIDlet, close the bluetooth connection
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		if (relay != null) relay.disconnect();

	}

	//obligatory method of MIDlet not used.
	protected void pauseApp() {

	}
	/**General Purpose method for reporting stuff
	 * @param _s  //text to report
	 */
	void put(String _s) {
		System.out.println(_s);
		mainForm.append(_s);
	}

	/**Creates a BlueTooth connection to a specified address, 
	 * listens for incoming bytes and send them http.
	 * @author Dano
	 */
	class BT2WebRelayThread extends Thread {

		//output stream for sending
		StreamConnection btConnection = null;

		/* Essence of the thread to accumulate bytes and then send them http
		 * 
		 */
		public void run() {

			try {
				//surrounds hardware address in bluetooth stuff. ":01" is for the serial service
				String BTurl = "btspp://" + BT_ADDRESS + ":01;authenticate=false;encrypt=false;master=false";
				put("Connecting to :" + BTurl);
				btConnection = (StreamConnection) Connector.open(BTurl);
				put("Connected");
				try {
					InputStream btInputStream = btConnection.openInputStream();
					OutputStream btOutputStream = btConnection.openOutputStream();
					//send a byte out in case other side is waiting to be prompted
					btOutputStream.write(65);
					String accumulatedFromBT = "";
					while (true) {
		
						//read in a byte at a time, this stops for the byte, that is why we are in a thread
						int BTInput = btInputStream.read();
					
						accumulatedFromBT = accumulatedFromBT + (char) BTInput;
						if (BTInput == TERMINATION_CHAR) {
							//send data to the web
							//mainForm.deleteAll();
							put("In From BlueTooth: " + accumulatedFromBT);
							try {
								String HTTPurl = WEB_ADDRESS + "?data=" + accumulatedFromBT;
								//start fresh with the accumulated
								accumulatedFromBT = "";
								put("Sending: " + HTTPurl);
								HttpConnection myHTTPConnection = (HttpConnection) Connector.open(HTTPurl);
								myHTTPConnection.setRequestMethod(HttpConnection.GET);
								//not much more to send because we sent the info on the url
								//listen for a response
								InputStream HTTPInputStream = myHTTPConnection.openDataInputStream();
								int HTTPInput;
								String response = "Server Response:";
								while ((HTTPInput = HTTPInputStream.read()) != -1) {
									response = response + (char) HTTPInput;
								}
								put("Response from Web: " + response);
								HTTPInputStream.close();
								myHTTPConnection.close();
							} catch (Exception e) {
								put("Problem with get " + WEB_ADDRESS);
							}
							//send a byte out in case other side is waiting to be prompted
							btOutputStream.write(65);

						}

					}
				} catch (IOException e) {
					put("Stopped Listening To BlueTooth");
				}
			} catch (IOException e) {
				put("Sorry but could not connect. to " + BT_ADDRESS);
			}
			disconnect();
		}

		void disconnect() {
			try {

				btConnection.close();
			} catch (Exception e) {
				put("Trouble Closing Connection.");

			}

		}

	}

}
